﻿using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ResourceBlender_Express {
    /// <summary>
    /// A form allowing a user to search for and select a resource
    /// </summary>
    public partial class WinFindResource : Window {
        private BackgroundWorker worker;
        private ObservableSortedDictionary<string, string> languages;
        private string applicationId = string.Empty;

        /// <summary>
        /// Gets the selected resource.
        /// </summary>
        /// <value>The selected resource.</value>
        public object SelectedResource {
            get { return lstResources.SelectedValue; }
        }

        /// <summary>
        /// Initializes a new <see cref="WinFindResource"/>.
        /// </summary>
        public WinFindResource() {
            InitializeComponent();
            chkOnlyExisting.Visibility = Visibility.Hidden;
            txtTranslation.Focus();
            LoadLanguages(string.Empty);
        }

        /// <summary>
        /// Initializes a new <see cref="WinFindResource"/> and searches for resources similar to the specified translation.
        /// </summary>
        /// <param name="translation">The translation.</param>
        /// <param name="applicationId">The application ID to use when filtering for existing resources.</param>
        public WinFindResource(RBTranslation translation, string applicationId) {
            DataContext = translation;
            if(applicationId.Length > 0) {
                this.applicationId = applicationId;
            } else {
                chkOnlyExisting.Visibility = Visibility.Hidden;
            }
            InitializeComponent();
            txtTranslation.Focus();
            ApplicationCommands.Find.Execute(null, txtTranslation);
            LoadLanguages(translation.LanguageCode);
        }

        /// <summary>
        /// Populates the Language ComboBox.
        /// </summary>
        /// <param name="selectedLanguage">The language to select.</param>
        private void LoadLanguages(string selectedLanguage) {
            SetStatus(true, "Loading available languages...");
            if(worker != null && worker.IsBusy) {
                while(worker.IsBusy) {
                    Thread.Sleep(500);
                }
            }
            worker = new BackgroundWorker();
            worker.DoWork += (s, dwe) => {
                Database db = null;
                try {
                    db = new Database();
                    dwe.Result = db.LoadUniqueLanguages();
                } catch(Exception ex) {
                    dwe.Result = ex.Message;
                } finally {
                    if(db != null) {
                        try {
                            db.CloseConnection();
                        } catch { }
                    }
                }
            };
            worker.RunWorkerCompleted += (s, rwe) => {
                SetStatus(false, null);
                if(rwe.Result is ObservableSortedDictionary<string, string>) {
                    ObservableSortedDictionary<string, string> langs = rwe.Result as ObservableSortedDictionary<string, string>;
                    if(langs.Count == 0) {
                        DialogBox.Show(this, "No resources have been added.\n\nBefore you can search for resources, at least one must be added", "No Resources", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Warning);
                        Close();
                    } else {
                        if(!langs.ContainsKey(selectedLanguage) && selectedLanguage.Length > 0) {
                            langs.Add(selectedLanguage, selectedLanguage);
                        }
                        this.languages = langs;
                        cboLanguages.ItemsSource = languages;
                        ApplicationCommands.Find.Execute(null, txtTranslation);
                    }
                } else {
                    DialogBox.Show(this, rwe.Result.ToString(), "Database Error", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Error);
                }
            };
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Sets the text on the status message.
        /// </summary>
        /// <param name="loading"><c>true</c> if the progress bar should be displayed, otherwise false.</param>
        /// <param name="message">The message.</param>
        private void SetStatus(bool loading, object message) {
            if(message == null) {
                lblStatus.Visibility = Visibility.Hidden;
            } else {
                lblStatus.Visibility = Visibility.Visible;
                lblStatus.Content = message;
            }
            prgStatus.Visibility = loading ? Visibility.Visible : Visibility.Hidden;
        }

        /// <summary>
        /// Clears the ListView when the selected language changes.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void cboLanguages_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            if(lstResources != null) {
                lstResources.DataContext = null;
            }
        }

        /// <summary>
        /// Searches for resources.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void FindResources(object sender, ExecutedRoutedEventArgs e) {
            if(cboLanguages.SelectedIndex < 0 || string.IsNullOrEmpty(txtTranslation.Text)) {
                return;
            }
            string languageCode = cboLanguages.SelectedValue.ToString(),
                   searchText;
            bool onlyExisting = chkOnlyExisting.IsChecked == true;
            switch(cboCriteria.SelectedIndex) {
                case 1:
                    searchText = txtTranslation.Text + '%';
                    break;
                case 2:
                    searchText = '%' + txtTranslation.Text;
                    break;
                case 0:
                default:
                    searchText = '%' + txtTranslation.Text + '%';
                    break;
            }
            SetStatus(true, "Searching...");
            if(worker != null && worker.IsBusy) {
                while(worker.IsBusy) {
                    Thread.Sleep(500);
                }
            }
            worker = new BackgroundWorker();
            worker.DoWork += (s, dwe) => {
                Database db = null;
                try {
                    db = new Database();
                    db.OpenConnection();
                    using(Database.Command cmd = db.CreateCommand()) {
                        StringBuilder sqlBuffer;
                        if(onlyExisting && applicationId.Length > 0) {
                            sqlBuffer = new StringBuilder("SELECT r.resourceid, r.translation, c.comment, (SELECT COUNT(language) FROM {0}resources WHERE resourceid = r.resourceid) AS numlanguages ")
                                                  .Append("FROM {0}elements AS e INNER JOIN {0}resources AS r ON r.resourceid = e.resourceid LEFT JOIN {0}resourcecomments AS c ON r.resourceid = c.resourceid ")
                                                  .Append("WHERE language = @language AND translation LIKE @translation AND applicationid = @application ORDER BY translation");
                            cmd.AddParameterWithValue("@application", applicationId);
                        } else {
                            sqlBuffer = new StringBuilder("SELECT r.resourceid, r.translation, c.comment, (SELECT COUNT(language) FROM {0}resources WHERE resourceid = r.resourceid) AS numlanguages ")
                                                  .Append("FROM {0}resources AS r LEFT JOIN {0}resourcecomments AS c ON r.resourceid = c.resourceid ")
                                                  .Append("WHERE language = @language AND translation LIKE @translation ORDER BY translation");
                        }
                        cmd.CommandText = string.Format(sqlBuffer.ToString(), db.TablePrefix);
                        cmd.AddParameterWithValue("@language", languageCode);
                        cmd.AddParameterWithValue("@translation", searchText);
                        Database.DataAdapter adapter = new Database.DataAdapter(cmd);
                        DataTable dtResults = new DataTable();
                        adapter.Fill(dtResults);
                        dwe.Result = dtResults;
                    }
                } catch(Exception ex) {
                    dwe.Result = ex.Message;
                } finally {
                    if(db != null) {
                        try {
                            db.CloseConnection();
                        } catch { }
                    }
                }
            };
            worker.RunWorkerCompleted += (s, rwe) => {
                if(rwe.Result is DataTable) {
                    DataTable dtResults = rwe.Result as DataTable;
                    lstResources.DataContext = dtResults;
                    int numResources = dtResults.Rows.Count;
                    SetStatus(false, numResources == 0 ? "No matches" : string.Format("{0} {1}", numResources, numResources == 1 ? "resource" : "resources"));
                } else {
                    DialogBox.Show(this, rwe.Result.ToString(), "Database Error", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Error);
                    SetStatus(false, null);
                }
            };
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Determines whether the Find Resources command can be executed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.CanExecuteRoutedEventArgs"/> instance containing the event data.</param>
        private void CanExecuteFindResources(object sender, CanExecuteRoutedEventArgs e) {
            e.CanExecute = !string.IsNullOrEmpty(txtTranslation.Text) && cboLanguages.SelectedIndex >= 0 && worker != null && !worker.IsBusy;
        }

        /// <summary>
        /// Selects a resource and returns a DialogResult of true.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void SelectResource(object sender, ExecutedRoutedEventArgs e) {
            DialogResult = true;
        }

        /// <summary>
        /// Determines whether the Select Resource command can be executed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.CanExecuteRoutedEventArgs"/> instance containing the event data.</param>
        private void CanExecuteSelectResource(object sender, CanExecuteRoutedEventArgs e) {
            e.CanExecute = lstResources.SelectedItem != null;
        }

        /// <summary>
        /// Closes the window.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void CloseWindow(object sender, ExecutedRoutedEventArgs e) {
            Close();
        }
    }
}
